package cn.sdhuijin.vms.service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import cn.sdhuijin.vms.dao.ICarRecordDao;
import cn.sdhuijin.vms.dao.ILeaveDao;
import cn.sdhuijin.vms.dao.IOrganizationDao;
import cn.sdhuijin.vms.dao.IPersonRecordDao;
import cn.sdhuijin.vms.model.Car;
import cn.sdhuijin.vms.model.CarRecord;
import cn.sdhuijin.vms.model.Leave;
import cn.sdhuijin.vms.model.Organization;
import cn.sdhuijin.vms.model.Person;
import cn.sdhuijin.vms.model.PersonRecord;
import cn.sdhuijin.vms.model.User;
import cn.sdhuijin.vms.util.OrgUtil;

@Service("myRecordService")
public class RecordService implements IRecordService {
	final Logger logger = LoggerFactory.getLogger(RecordService.class);
	@Inject
	private IPersonRecordDao personRecordDao;
	@Inject
	private ICarRecordDao carRecordDao;
	@Inject
	private ILeaveDao leaveDao;
	@Inject
	private IOrganizationDao organizationDao;

	@Override
	public Page<PersonRecord> getPersonRecordList(Integer page, Integer rows) {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.hasRole("admin")) {
			return personRecordDao.findAll(new PageRequest(page, rows,
					new Sort(Direction.DESC, "date")));
		} else {
			Organization org = ((User) currentUser.getPrincipal())
					.getOrganization();
			return personRecordDao.findByOrganizationIdIn(OrgUtil
					.getAllIds(org), new PageRequest(page, rows, new Sort(
					Direction.DESC, "date")));
		}
	}

	@Override
	public Page<CarRecord> getCarRecordList(Integer page, Integer rows) {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.hasRole("admin")) {
			return carRecordDao.findAll(new PageRequest(page, rows, new Sort(
					Direction.DESC, "date")));
		} else {
			Organization org = ((User) currentUser.getPrincipal())
					.getOrganization();
			return carRecordDao.findByOrganizationIdIn(OrgUtil.getAllIds(org),
					new PageRequest(page, rows,
							new Sort(Direction.DESC, "date")));
		}
	}

	@Override
	public Boolean addIn(Person person, Organization org, Date date) {
		Boolean result = false;
		List<Leave> leaves = leaveDao.findByPersonIdAndDate(person.getId(),
				date);
		PersonRecord pr = new PersonRecord();
		pr.setPerson(person);
		pr.setType("进入");
		pr.setOrganization(org);
		pr.setDate(date);
		if (!leaves.isEmpty()) {
			// 有合法外出申请
			pr.setLeave(leaves.get(0));
			result = true;
		}
		personRecordDao.save(pr);
		return result;
	}

	@Override
	public Boolean addOut(Person person, Organization org, Date date) {
		Boolean result = false;
		List<Leave> leaves = leaveDao.findByPersonIdAndDate(person.getId(),
				date);
		PersonRecord pr = new PersonRecord();
		pr.setPerson(person);
		pr.setType("外出");
		pr.setOrganization(org);
		pr.setDate(date);
		if (!leaves.isEmpty()) {
			// 有合法外出申请
			pr.setLeave(leaves.get(0));
			result = true;
		}
		personRecordDao.save(pr);
		return result;
	}

	@Override
	public Boolean addIn(Car car, Organization org, Date date) {
		CarRecord cr = new CarRecord();
		cr.setCar(car);
		cr.setType("进入");
		cr.setOrganization(org);
		cr.setDate(date);
		carRecordDao.save(cr);
		return true;
	}

	@Override
	public Boolean addOut(Car car, Organization org, Date date) {
		CarRecord cr = new CarRecord();
		cr.setCar(car);
		cr.setType("外出");
		cr.setOrganization(org);
		cr.setDate(date);
		carRecordDao.save(cr);
		return true;
	}

	@Override
	public Page<PersonRecord> getPersonRecordListByDateAndName(Integer page,
			Integer rows, Date startTime, Date endTime, String name,
			String orgId) {
		try {
			name = new String(name.getBytes("iso8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return personRecordDao
				.findByDateBetweenAndPersonNameLikeAndPersonOrganizationIdIn(
						startTime, endTime, "%" + name + "%", OrgUtil
								.getAllIds(organizationDao.findOne(Long
										.valueOf(orgId))), new PageRequest(
								page, rows, new Sort(Direction.DESC, "date")));
	}

	@Override
	public List<CarRecord> getCarRecordListByDateAndLicense(Date startTime,
			Date endTime, String license, String orgId) {
		return carRecordDao
				.findByCarOrganizationIdInAndDateBetweenAndCarLicenseLike(
						OrgUtil.getAllIds(organizationDao.findOne(Long
								.valueOf(orgId))), startTime, endTime, "%"
								+ license + "%");
	}

	@Override
	public Page<CarRecord> getCarRecordListByDateAndLicense(Integer page,
			Integer rows, Date startTime, Date endTime, String license,
			String orgId) {
		try {
			license = new String(license.getBytes("iso8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return carRecordDao
				.findByCarOrganizationIdInAndDateBetweenAndCarLicenseLike(
						OrgUtil.getAllIds(organizationDao.findOne(Long
								.valueOf(orgId))), startTime, endTime, "%"
								+ license + "%", new PageRequest(page, rows,
								new Sort(Direction.DESC, "date")));
	}

	@Override
	public List<PersonRecord> getPersonRecordListByDateAndName(Date startTime,
			Date endTime, String name, String orgId) {
		return personRecordDao
				.findByPersonOrganizationIdInAndDateBetweenAndPersonNameLike(
						OrgUtil.getAllIds(organizationDao.findOne(Long
								.valueOf(orgId))), startTime, endTime, "%"
								+ name + "%");
	}
}
